//
//  MoreTripDetailViewController.m
//  lvtu
//
//  Created by martin on 12-9-7.
//
//

#import "MoreTripDetailViewController.h"
#import "NetDataSource.h"
#import "EventThumbViem.h"
#import "NSDate+Helper.h"
#import "wxAppDelegate.h"

@interface MoreTripDetailViewController ()

@end

@implementation MoreTripDetailViewController
@synthesize delegate;
@synthesize sumTripInfo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (id)initWithTravelInfo:(TripInfo*)info recommondInfo:(RecommendTripInfo*)sumInfo Index:(NSInteger)index
{
    self = [super init];
    if (self) {
        // Custom initialization
        tripinfo = info;
        sumTripInfo = sumInfo;
        dateIndex = index;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [tempLabel setText:@"旅途详情"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    
    UIImage* backImage = [UIImage imageNamed:@"btn_back_normal.png"];
    UIButton* leftbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftbutton.frame = CGRectMake(0, 0, backImage.size.width, backImage.size.height);
    [leftbutton setBackgroundImage:backImage forState:UIControlStateNormal];
    [leftbutton setBackgroundImage:[UIImage imageNamed:@"btn_back_press.png"] forState:UIControlStateHighlighted];
    [leftbutton addTarget:self action:@selector(backButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbutton];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    [backButtonItem release];
    
    cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 15, 50, 20)];
    cityLabel.font = [UIFont boldSystemFontOfSize:12];
    cityLabel.backgroundColor = [UIColor clearColor];
    cityLabel.textColor = [UIColor colorWithRed:252/255.0 green:100/255.0 blue:22/255.0 alpha:1.0];
    cityLabel.textAlignment = UITextAlignmentLeft;
    cityLabel.text = @"";
    [self.view addSubview:cityLabel];
    [cityLabel release];
    
    currentDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 15, 50, 20)];
    currentDateLabel.font = [UIFont boldSystemFontOfSize:15];
    currentDateLabel.backgroundColor = [UIColor clearColor];
    currentDateLabel.textColor = [UIColor colorWithRed:252/255.0 green:100/255.0 blue:22/255.0 alpha:1.0];
    currentDateLabel.textAlignment = UITextAlignmentLeft;
    [self.view addSubview:currentDateLabel];
    [currentDateLabel release];
    
    totleDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(135, 16, 160, 20)];
    totleDateLabel.font = [UIFont boldSystemFontOfSize:14];
    totleDateLabel.backgroundColor = [UIColor clearColor];
    totleDateLabel.textColor = [UIColor colorWithRed:122/255.0 green:143/255.0 blue:68/255.0 alpha:1];
    totleDateLabel.textAlignment = UITextAlignmentLeft;
    [self.view addSubview:totleDateLabel];
    [totleDateLabel release];
    
    UIImage *eventShowViewBgImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg_whiteframe.png" ofType:nil]];
    eventShowBgView = [[UIImageView alloc] initWithImage:[eventShowViewBgImage stretchableImageWithLeftCapWidth:30 topCapHeight:10]];
    eventShowBgView.userInteractionEnabled = YES;
    [eventShowViewBgImage release];
    [eventShowBgView setFrame:CGRectMake(30, 40, 260, 290)];
    [self.view addSubview:eventShowBgView];
    
    eventShowView = [[UIScrollView alloc] initWithFrame:CGRectMake(10, 10, 240, 270)];
    eventShowView.backgroundColor = [UIColor clearColor];
    eventShowView.contentSize = CGSizeMake(240, 270);
    eventShowView.pagingEnabled = NO;
    eventShowView.scrollEnabled = YES;
    eventShowView.clipsToBounds = YES;
    eventShowView.scrollsToTop = YES;
    eventShowView.showsVerticalScrollIndicator = YES;
    eventShowView.showsHorizontalScrollIndicator = NO;
    //    eventShowView.delegate = self;
    [eventShowBgView addSubview:eventShowView];
    
    praiseButton = [UIButton buttonWithType:UIButtonTypeCustom];
	praiseButton.frame = CGRectMake(0, 322, 106, 48);
    [praiseButton setBackgroundImage:[UIImage imageNamed:@"btn_like_normal.png"] forState:UIControlStateNormal];
    [praiseButton setBackgroundImage:[UIImage imageNamed:@"btn_like_press.png"] forState:UIControlStateHighlighted];
    [praiseButton setBackgroundImage:[UIImage imageNamed:@"btn_like_press.png"] forState:UIControlStateSelected];
	[praiseButton addTarget:self action:@selector(praiseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:praiseButton];
    praiseLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 8, 60, 30)];
    praiseLabel.text = [NSString stringWithFormat:@"称赞(%@)",tripinfo.praisecount];
    praiseLabel.backgroundColor = [UIColor clearColor];
    praiseLabel.font = [UIFont systemFontOfSize:12.0f];
    [praiseButton addSubview:praiseLabel];
    [praiseButton setEnabled:NO];
    
    favorbutton = [UIButton buttonWithType:UIButtonTypeCustom];
	favorbutton.frame = CGRectMake(107, 322, 106, 48);
    [favorbutton setBackgroundImage:[UIImage imageNamed:@"btn_collect_normal.png"] forState:UIControlStateNormal];
    [favorbutton setBackgroundImage:[UIImage imageNamed:@"btn_collect_press.png"] forState:UIControlStateHighlighted];
    [favorbutton setBackgroundImage:[UIImage imageNamed:@"btn_collect_press.png"] forState:UIControlStateSelected];
	[favorbutton addTarget:self action:@selector(favorButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:favorbutton];
    collectLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 8, 60, 30)];
    collectLabel.text = [NSString stringWithFormat:@"收藏(%@)",tripinfo.favorcount];
    collectLabel.backgroundColor = [UIColor clearColor];
    collectLabel.font = [UIFont systemFontOfSize:12.0f];
    [favorbutton addSubview:collectLabel];
    
    commentbutton = [UIButton buttonWithType:UIButtonTypeCustom];
	commentbutton.frame = CGRectMake(214, 322, 106, 48);
    [commentbutton setBackgroundImage:[UIImage imageNamed:@"btn_comment_normal.png"] forState:UIControlStateNormal];
    [commentbutton setBackgroundImage:[UIImage imageNamed:@"btn_comment_press.png"] forState:UIControlStateHighlighted];
    [commentbutton setBackgroundImage:[UIImage imageNamed:@"btn_comment_press.png"] forState:UIControlStateSelected];
	[commentbutton addTarget:self action:@selector(commentButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:commentbutton];
    commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 8, 60, 30)];
    commentLabel.text = [NSString stringWithFormat:@"评论(%@)",tripinfo.commentcount];
    commentLabel.backgroundColor = [UIColor clearColor];
    commentLabel.font = [UIFont systemFontOfSize:12.0f];
    [commentbutton addSubview:commentLabel];
    
    preButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 155, 26, 50)];
    [preButton setImage:[UIImage imageNamed:@"btn_prev_normal.png"] forState:UIControlStateNormal];
    [preButton setImage:[UIImage imageNamed:@"btn_prev_press.png"] forState:UIControlStateHighlighted];
    [preButton addTarget:self action:@selector(preDayPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:preButton];
    
    if (dateIndex < [tripinfo.datedic count]) {
        nextButton = [[UIButton alloc] initWithFrame:CGRectMake(294, 155, 26, 50)];
        [nextButton setImage:[UIImage imageNamed:@"btn_next_normal.png"] forState:UIControlStateNormal];
        [nextButton setImage:[UIImage imageNamed:@"btn_next_press.png"] forState:UIControlStateHighlighted];
        [nextButton addTarget:self action:@selector(nextDayPressed) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:nextButton];
    }
    
    NSDate* date = [NSDate dateWithDateString:tripinfo.starttime] ;
    NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
    timeInterval += 24*60*60*(dateIndex-1);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateString = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
    [dateFormatter release];
    
    [[DataSource shareInstance] setDate:dateString];
    currentDateLabel.text = [NSString stringWithFormat:@"第%d天",dateIndex];
    totleDateLabel.text = [NSString stringWithFormat:@"/ 共%d天 %@",[tripinfo.datedic count],dateString];
    
    [self reloadEventShowView];
    
//    if ([wxAppDelegate getAppDelegate].isLogin) {
//        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:tripId,@"c_travel_line_id",nil];
//        CoreMsg* msg = [[CoreMsg alloc] init];
//        msg.data = PRAISETRAVEL;
//        msg.ui_delegate = self;
//        
//        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_line_praise" postInfo:info userInfo:msg];
//        
//        info = [[NSDictionary alloc] initWithObjectsAndKeys:tripId,@"c_travel_line_id",nil];
//        msg = [[CoreMsg alloc] init];
//        msg.data = FAVORTRAVEL;
//        msg.ui_delegate = self;
//        
//        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_line_favor" postInfo:info userInfo:msg];
//    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)reloadEventShowView
{
    NSArray* eventArray = [[DataSource shareInstance] getCurrentEvent];
    if ([eventArray count] != 0) {
        eventShowBgView.hidden = NO;
        eventShowView.hidden = NO;
        
        NSInteger height = [eventArray count]/3;
        if ([eventArray count]%3 > 0) {
            height ++;
        }
        [eventShowView setContentSize:CGSizeMake(240, 90*height)];
        int index = 0;
        for (PlaceInfo* info in eventArray) {
            if ([cityLabel.text isEqual: @""]) {
                for (CityInfo* city in [DataSource shareInstance].cityArray) {
                    if ([info.cityid isEqualToString:city.cityid]) {
                        cityLabel.text = city.name;
                        break;
                    }
                }
                cityLabel.text = [NSString stringWithFormat:@"[%@]",cityLabel.text];
            }
            EventThumbViem* view = [[EventThumbViem alloc] initWithFrame:CGRectMake((76+5)*(index%3)+2, index/3*90, 76, 90) Data:info];
            [view setViewType:NO];
            [eventShowView addSubview:view];
            [view release];
            index ++;
        }
    }
    else
    {
        eventShowBgView.hidden = YES;
        eventShowView.hidden = YES;
    }
}

- (void)sendCommentSuccess
{
    commentLabel.text = [NSString stringWithFormat:@"评论(%d)",[tripinfo.commentcount intValue]+1];
    tripinfo.commentcount = [NSString stringWithFormat:@"%d",[tripinfo.commentcount intValue]+1];
}

- (void)backButtonPress:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - button
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 10001)
    {
        if (buttonIndex == 1) {
            [[wxAppDelegate getAppDelegate] popAllViewController];
            [[wxAppDelegate getAppDelegate] launchFirstView];
        }
    }
}

- (void)praiseButtonPressed:(id)sender
{
    if ([wxAppDelegate getAppDelegate].isLogin == NO) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要登录才能称赞哟。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 10001;
        [alert show];
        [alert release];
        return;
    }
    if (praiseButton.isSelected == NO) {
        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:tripId,@"c_travel_line_id",nil];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = PRAISETRAVEL;
        msg.ui_delegate = self;
        
        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_line_praise" postInfo:info userInfo:msg];
        
        [praiseButton setSelected:YES];
        praiseLabel.text = [NSString stringWithFormat:@"称赞(%d)",[tripinfo.praisecount intValue]+1];
        tripinfo.praisecount = [NSString stringWithFormat:@"%d",[tripinfo.praisecount intValue]+1];
    }
//    [praiseButton setSelected:YES];
//    praiseLabel.text = [NSString stringWithFormat:@"称赞(%d)",[tripinfo.praisecount intValue]+1];
//    tripinfo.praisecount = [NSString stringWithFormat:@"%d",[tripinfo.praisecount intValue]+1];
}

- (void)favorButtonPressed:(id)sender
{
    if ([wxAppDelegate getAppDelegate].isLogin == NO) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要登录才能收藏哟。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 10001;
        [alert show];
        [alert release];
        return;
    }
    if (favorbutton.isSelected == NO) {
        NSDictionary* info = [[NSDictionary alloc] initWithObjectsAndKeys:tripId,@"c_travel_line_id",nil];
        CoreMsg* msg = [[CoreMsg alloc] init];
        msg.data = FAVORTRAVEL;
        msg.ui_delegate = self;
        
        [[NetDataSource shareInstance]postTo:@"http://www.wxlvtu.com/?a=page_line_favor" postInfo:info userInfo:msg];
        
        [favorbutton setSelected:YES];
        collectLabel.text = [NSString stringWithFormat:@"收藏(%d)",[tripinfo.favorcount intValue]+1];
        tripinfo.favorcount = [NSString stringWithFormat:@"%d",[tripinfo.favorcount intValue]+1];
    }
    
//    [favorbutton setSelected:YES];
//    collectLabel.text = [NSString stringWithFormat:@"收藏(%d)",[tripinfo.favorcount intValue]+1];
}

- (void)commentButtonPressed:(id)sender
{
    if ([wxAppDelegate getAppDelegate].isLogin == NO) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要登录才能评论哟。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 10001;
        [alert show];
        [alert release];
        return;
    }
    MessageInfo* info = [[MessageInfo alloc] init];
    info.travellineid = tripId;
    info.name = tripinfo.name;
    info.creattime = tripinfo.creattime;
    info.commentcount = tripinfo.commentcount;
    
    CommentDetailViewController * travelDetailViewController = [[CommentDetailViewController alloc] initWithMsgInfo:info];
    travelDetailViewController.delegate = self;
    [self.navigationController pushViewController:travelDetailViewController animated:YES];
    [travelDetailViewController release];
}

- (void)preDayPressed
{
    [delegate touchPreDayButton];
}

- (void)nextDayPressed
{
    [delegate touchNextDayButton];
}

#pragma -mark DataSourceDelegate

- (void)onDataSourceSucCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if([coreMsg.data isEqual: PRAISETRAVEL])
    {
        [praiseButton setSelected:YES];
    }
    else if([coreMsg.data isEqual: FAVORTRAVEL])
    {
        [favorbutton setSelected:YES];
    }
}

- (void)onDataSourceFailCallback:(CoreMsg *)coreMsg withData:(id)data
{
    if([coreMsg.data isEqual: PRAISETRAVEL])
    {
        if ([data isEqual:@"exited"]) {
            [praiseButton setSelected:YES];
            
            praiseLabel.text = [NSString stringWithFormat:@"称赞(%d)",[tripinfo.praisecount intValue]-1];
            tripinfo.praisecount = [NSString stringWithFormat:@"%d",[tripinfo.praisecount intValue]-1];
        }
        else
        {
//            [praiseButton setSelected:NO];
        }
    }
    else if([coreMsg.data isEqual: FAVORTRAVEL])
    {
        if ([data isEqual:@"exited"]) {
            [favorbutton setSelected:YES];
            collectLabel.text = [NSString stringWithFormat:@"收藏(%d)",[sumTripInfo.favorcount intValue]+1];
            sumTripInfo.favorcount = [NSString stringWithFormat:@"%d",[sumTripInfo.favorcount intValue]+1];
        }
        else
        {
//            [praiseButton setSelected:NO];
        }
    }
}

@end
